﻿

#region Using Statements

using UnityEngine;
using System.Collections.Generic;

#endregion


[RequireComponent(typeof(Rigidbody2D))]
/// <summary>
/// 
/// </summary>
public class Boomerang : MonoBehaviour
{

    #region Members

    public float forceRate = 100.0f;

    public float baseForce = 300.0f;

    public float baseSpinRate = 50.0f;

    public float velocitySpinRate = 100.0f;

    public float velocitySpinPower = 0.3f;

    public float initialTestForce = 1000.0f;

    public float damping = 0.15f;

    public GameObject master;

    public float currentForce { get; set; }

    #endregion


    #region Init

	/// <summary>
    /// 
    /// </summary>
    protected virtual void Awake()
    {

    }


    /// <summary>
    /// 
    /// </summary>
    protected virtual void Start()
    {
        currentForce = baseForce;
        rigidbody2D.AddForce((Vector2.right + Vector2.up) * initialTestForce);
    }

    #endregion


    #region Update

    /// <summary>
    /// 
    /// </summary>
    protected virtual void Update()
    {
        GameObject target = master == null ? GameObject.FindGameObjectWithTag("Player") : master;
        Vector3 diff = target.transform.position - transform.position;
        Vector3 dir = diff.normalized;

        rigidbody2D.AddForce(dir * currentForce * Time.deltaTime);

        currentForce += forceRate * Time.deltaTime;
        currentForce *= Util.DampingCoefficient(damping);

        rigidbody2D.AddTorque((baseSpinRate + velocitySpinRate * Mathf.Pow(rigidbody2D.velocity.magnitude, velocitySpinPower)) * Time.deltaTime);
    }

    #endregion


    #region Collision

    /// <summary>
    /// 
    /// </summary>
    /// <param name="coll"></param>
    void OnCollisionEnter2D(Collision2D coll)
    {
        coll.gameObject.SendMessage("OnHitByBoomerang", this, SendMessageOptions.DontRequireReceiver);
    }

    #endregion

}